package com.cykj.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.cykj.common.dto.ResponseDTO;
import com.cykj.common.entity.*;
import com.cykj.common.utils.SaTokenUtils;
import com.cykj.user.mapper.UserMapper;
import com.cykj.user.service.IUserService;
import com.cykj.user.util.LatLngDistanceUtil;
import com.cykj.user.vo.CareerExpectVO;
import com.cykj.user.vo.RecruitInfoVO;
import com.cykj.user.vo.UserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * @BelongsProject: smart_recruit_backend
 * @BelongsPackage: com.cykj.user.service.impl
 * @Author: 浮行
 * @CreateTime: 2025-08-16 09:59
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class UserServiceImpl implements IUserService {
    @Value("${fileUrl}")
    private String fileUrl;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ResponseDTO updatePassword(UserVO userVO) {
        UserDO userDO = userMapper.selectUserPassword(userVO);
        if(userDO.getPassword().equals(userVO.getOldPwd()) ){
            Integer res = userMapper.updatePassword(userVO);
            if(res > 0){
                return ResponseDTO.success();
            }
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO update(UserVO userVO) {
        Integer res = userMapper.update(userVO);
        if(res > 0 ){
            return ResponseDTO.success();
        }

        return ResponseDTO.error();
    }

    //用户登录
    @Override
    public ResponseDTO login(UserVO userVO) {
        UserDO login = userMapper.login(userVO);
        if(login != null){
            String token = SaTokenUtils.saLogin("user", login.getUserId());
            UserDO EphemeralData = userMapper.getEphemeralData(login.getUserId());
            if(EphemeralData.getHeadIcon() != null){
                //拼接头像url+相对路径
                EphemeralData.setHeadIcon(fileUrl + EphemeralData.getHeadIcon());
            }
            redisTemplate.opsForValue().set("user:"+login.getUserId(),EphemeralData);
            userVO.setUserId(login.getUserId());
            Integer careerExpectData = userMapper.getCareerExpectData(userVO);
            if(careerExpectData != null && careerExpectData != 0){
                return ResponseDTO.success(token);
            }
            return new ResponseDTO(201,"未填写求职需求",token);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO getEphemeralData(String token) {
        // 获取登录ID（可能是String或Integer）
        Object loginId = StpUtil.getLoginIdByToken(token);
        Integer id = null;

        // 安全转换ID
        if (loginId instanceof Integer) {
            id = (Integer) loginId;
        } else if (loginId instanceof String) {
            try {
                id = Integer.parseInt((String) loginId);
            } catch (NumberFormatException e) {
                return ResponseDTO.codeError("用户ID格式错误");
            }
        } else {
            return ResponseDTO.codeError("不支持的ID类型");
        }

        // 从Redis获取数据
        Object userObj = redisTemplate.opsForValue().get("user:" + id);

        // 处理Redis数据
        if (userObj instanceof com.alibaba.fastjson.JSONObject) {
            UserDO userDO = ((com.alibaba.fastjson.JSONObject) userObj).toJavaObject(UserDO.class);
            return ResponseDTO.success(userDO);
        } else if (userObj instanceof UserDO) {
            return ResponseDTO.success(userObj);
        }
        return ResponseDTO.codeError("临时数据获取错误");
    }

    @Override
    public ResponseDTO getPositionTypeAndFirst() {
        List<JobTypeDO> jobTypeDOS = userMapper.getPositionType();
        List<RegionDO> regionDOS = userMapper.getFirst();
        List<IndustryDO> industryDOS = userMapper.getIndustrys();
        if(jobTypeDOS != null && regionDOS != null && industryDOS != null){
            HashMap<String , Object> map = new HashMap<>();
            map.put("jobTypeDOS", jobTypeDOS);
            map.put("regionDOS", regionDOS);
            map.put("industryDOS", industryDOS);
            return ResponseDTO.success(map);
        }
        return ResponseDTO.error();
    }


    @Override
    public ResponseDTO getJobsByTypeId(Integer jobTypeId) {
        List<JobDO> jobDOS = userMapper.getJobsByTypeId(jobTypeId);
        if (jobDOS != null && jobDOS.size() > 0){
            return ResponseDTO.success(jobDOS);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO getCountiesByProvinceId(Integer provinceId) {
        List<RegionDO> regionDOS = userMapper.getCountiesByProvinceId(provinceId);
        if (regionDOS != null && regionDOS.size() > 0){
            return ResponseDTO.success(regionDOS);
        }
        return ResponseDTO.error();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseDTO submitCareerExpectInfo(CareerExpectVO careerExpectVO) {
        Integer ic = userMapper.insertCareerExpect(careerExpectVO);
        Integer iu = userMapper.updateUserInfo(careerExpectVO);
        if(ic != null && iu != null){
            if(ic + iu >= 2){
                UserDO EphemeralData = userMapper.getEphemeralData(careerExpectVO.getUserId());
                if(EphemeralData.getHeadIcon() != null){
                    //拼接头像url+相对路径
                    EphemeralData.setHeadIcon(fileUrl + EphemeralData.getHeadIcon());
                }
                redisTemplate.opsForValue().set("user:"+careerExpectVO.getUserId(),EphemeralData);
                return ResponseDTO.success();
            }
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO submitUserInfo(UserVO userVO) {
        if (emailService.verifyCaptcha(userVO.getEmail(), userVO.getEmailCode())) {
            try{
                Integer i = userMapper.submitUserInfo(userVO);
                if(i != null && i > 0){
                    return ResponseDTO.success(userVO);
                }
            }catch (Exception e){
                return ResponseDTO.error("邮箱已被使用");
            }
        }
        return ResponseDTO.error("验证码已过期");
    }

    @Override
    public ResponseDTO getCareerExpectByUserId(Integer userId) {
        List<CareerExpectDO> careerExpectDOS = userMapper.getCareerExpectByUserId(userId);
        if(careerExpectDOS != null && careerExpectDOS.size() > 0){
            return ResponseDTO.success(careerExpectDOS);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO getRegion(Integer regionId) {
        RegionDO regionDO = userMapper.getRegion(regionId);
        if (regionDO != null){
            return ResponseDTO.success(regionDO);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO recommendedRecruit(RecruitInfoVO recruitInfoVO, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<RecruitInfoDO> recruitInfoDOS = userMapper.recommendedRecruit(recruitInfoVO);
        return ResponseDTO.success(new PageInfo<>(recruitInfoDOS));
    }


    @Override
    public ResponseDTO deleteCareerExpect(Integer expectId) {
        Integer i = userMapper.deleteCareerExpect(expectId);
        if(i != null && i > 0){
            return ResponseDTO.success();
        }
        return ResponseDTO.error("删除失败");
    }

    @Override
    public ResponseDTO addCareerExpect(CareerExpectVO careerExpectVO) {
        Integer i = userMapper.addCareerExpect(careerExpectVO);
        if(i != null && i > 0){
            return ResponseDTO.success();
        }
        return ResponseDTO.error("添加失败");
    }

    @Override
    public ResponseDTO updateCareerExpectationRegion(CareerExpectVO careerExpectVO) {
        Integer i = userMapper.updateCareerExpectationRegion(careerExpectVO);
        if(i != null && i > 0){
            return ResponseDTO.success();
        }
        return ResponseDTO.error("修改失败");
    }

    @Override
    public ResponseDTO updateCareerExpectationRegionIsNull(CareerExpectVO careerExpectVO) {
        Integer i = userMapper.updateCareerExpectationRegionIsNull(careerExpectVO);
        if(i != null && i > 0){
            return ResponseDTO.success();
        }
        return ResponseDTO.error("修改失败");
    }

    @Override
    public ResponseDTO getRecruitAndElse(Integer recruitId,Integer userId) {
        RecruitInfoDO recruitInfoDO = userMapper.getRecruitAndElse(recruitId,userId);
        if(recruitInfoDO != null){
            return ResponseDTO.success(recruitInfoDO);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO getCompanyInfoByCompanyId(Integer companyId) {
        CompanyDO companyDO = userMapper.getCompanyInfoByCompanyId(companyId);
        System.out.println(companyDO);
        if(companyDO != null){
            return ResponseDTO.success(companyDO);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO search(String searchKeyword, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<RecruitInfoDO> recruitInfoDOS = userMapper.search(searchKeyword);
        return ResponseDTO.success(new PageInfo<>(recruitInfoDOS));
    }

    @Override
    public ResponseDTO getInterview(Integer userId) {
        List<InterviewDetailDO> interviewDetailDOList = userMapper.getInterview(userId);
        return ResponseDTO.success(interviewDetailDOList);
    }

    @Override
    public ResponseDTO getInterviewDeta(Integer bookingId) {
        InterviewDetailDO interviewDetailDO = userMapper.getInterviewDeta(bookingId);
        if(interviewDetailDO != null){
            return ResponseDTO.success(interviewDetailDO);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO getOrderByUserId(Integer userId) {
        List<OrderDO> orderDOS = userMapper.getOrderByUserId(userId);
        if(orderDOS != null){
            return ResponseDTO.success(orderDOS);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO getOrderInfo(Integer orderId) {
        OrderDO orderDO = userMapper.getOrderInfo(orderId);
        if(orderDO != null){
            return ResponseDTO.success(orderDO);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO getJuLi(Double lat, Double lng, Integer companyId) {
        String companyLocationInfo = userMapper.getCompanyLocationInfo(companyId);
        if(companyLocationInfo != null){
            String[] split = companyLocationInfo.split("%#&");
            System.out.println(split);
            Double lat1 = Double.parseDouble(split[0]);
            Double lng1 = Double.parseDouble(split[1]);
            double v = LatLngDistanceUtil.calculateDistance(lat, lng, lat1, lng1);
            return ResponseDTO.success(v);
        }
        return ResponseDTO.error();
    }

    @Override
    public ResponseDTO collectRecruit(Integer userId, Integer recruitId,Integer isNo) {
        Integer i = 0;
        if(isNo == 0){
            i = userMapper.collectRecruit(userId,recruitId);
            if(i > 0){
                return ResponseDTO.success("收藏成功");
            }
        }else{
            i = userMapper.deleteRecruit(userId,recruitId);
            if(i > 0){
                return ResponseDTO.success("取消收藏成功");
            }
        }
        return ResponseDTO.error();
    }
}
